<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #default>
          <span>总记录数: {{ total }} 条</span>
        </template>

        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleExport">excel导出</el-button>
          <el-button type="primary" size="small">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table v-loading="this.$store.state.logoing" border :data="list">
          <el-table-column label="序号" type="index" :index="handleIndex" sortable="" />
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formatType" sortable="" />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template v-slot="{row}">
              {{ timeData(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" prop="enableState" sortable="" />
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="PopUpRoleBox(row.id)">角色</el-button>
              <el-button size="small" type="text" @click="handleDelete(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <div style="height: 60px; margin-top: 10px">
          <el-pagination :total="total" layout="sizes, prev, pager, next" :current-page="filterParams.page" :page-size="filterParams.size" :page-sizes="[1, 2, 5, 10, 15]" @current-change="currentChange" @size-change="sizeChange" />
        </div>
      </el-card>
    </div>
    <!-- 角色弹窗 -->
    <AssignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
  </div>
</template>

<script>
import { reqGetEmployeeList, reqDelEmployeeAPI } from '@/api/employees'
import AssignRole from './components/AssignRole'
import moment from 'moment'
import Types from '@/api/constant/employees'
export default {
  name: 'Employees',
  components: { AssignRole },
  data () {
    return {
      // 角色标识
      showRoleDialog: false,
      userId: '',
      // 敞亮
      hireType: Types.hireType,
      // 员工列表数据
      list: [],
      // 列表总数
      total: 0,
      // 查询参数
      filterParams: {
        page: 1,
        size: 10
      }
    }
  },
  created () {
    this.loadEmployeeList()
  },
  methods: {
    // 获取员工列表数据
    async loadEmployeeList () {
      try {
        const ret = await reqGetEmployeeList(this.filterParams)
        this.list = ret.data.rows
        this.total = ret.data.total
        if (!ret.success) {
          this.$message.error(ret.message)
        }
      } catch {
        this.$message.error('获取员工列表失败')
      }
    },
    // 页面配置
    async currentChange (page) {
      this.filterParams.page = page
      await this.loadEmployeeList()
    },
    async sizeChange (pagesize) {
      this.filterParams.size = pagesize
      await this.loadEmployeeList()
    },
    // 阿斯白送
    formatType ({ formOfEmployment }) {
      const info = this.hireType.find(item => parseInt(item.id) === parseInt(formOfEmployment))
      if (info) {
        return info.value
      } else {
        return '其他'
      }
    },
    handleIndex (index) {
      // 形参index表示列表数据的索引，从0开始
      // 动态计算累加的索引
      // (当前页码 - 1) * 每页的条数
      const { page, size } = this.filterParams
      return (page - 1) * size + 1 + index
    }, // 删除角色
    async handleDelete (id) {
      try {
        // 删除前进行提示
        const ret = await this.$confirm('确认要删除角色吗？, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        // 点击了取消按钮
        if (ret === 'cancel') return
        // 点击确定，进行删除
        const result = await reqDelEmployeeAPI(id)
        console.log(result)
        if (result.code === 10000) {
          // 删除成功，刷新列表
          this.loadEmployeeList()
          this.$message.success('删除成功')
        } else {
          this.$message.error(result.message)
        }
      } catch {
        this.$message.error('删除失败')
      }
    },
    // 格式化时间
    timeData (time) {
      return moment(time).format('YYYY-MM-DD')
    },
    // 角色弹窗
    PopUpRoleBox (id) {
      this.userId = id
      this.showRoleDialog = true
    },
    // ex导出
    async handleExport () {
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const ret = await reqGetEmployeeList({
        page: 1,
        size: 1000
      })
      const list = this.getExportData(headers, ret.data.rows)
      const obj = Object.keys(headers)
      console.log(obj)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: obj, // 表头 必填
          data: list, // 具体数据 必填
          filename: 'excel-list', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },
    // 获取要导出的数据格式：二维数组
    getExportData (headers, rawData) {
      const arr = []
      rawData.forEach(item => {
        const arr2 = []
        for (const key in headers) {
          const enKey = headers[key]
          if (['timeOfEntry', 'correctionTime'].includes(enKey)) {
            let timexx = moment(item[enKey]).format('YYYY-MM-DD')
            if (timexx === 'Invalid date') {
              timexx = '无'
            }
            console.log(timexx)
            arr2.push(timexx)
          } else {
            arr2.push(item[enKey])
          }
        }
        arr.push(arr2)
      })
      return arr
    }
  }
}

</script>

<style lang="scss" scoped>
</style>
